<?php
/**
 * 房源模型
 */

namespace app\crontab\model;

use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Mongo;
use custom\TencentMap;
use map\BaiDu;
use think\Db;
use think\Exception;

class House extends BaseModel {

    protected $autoWriteTimestamp = true;
    protected $createTime = 'itime';
    protected $updateTime = 'utime';

    /**
     * 房源基本信息
     * @param $params
     * @return bool
     * @throws Exception
     */
    public function edit(&$params) {
        // 不存在就添加，存在不做变化
        if (!$old = $this->field('auction_id,id')->where(['sn' => $params['sn']])->find()) {
            // 新增房源
            if (!$id = $this->customName('erp_house')->customInsert($params)) {
                throw new Exception('新增房源失败', RespCode::PARAMS_ERR);
            }
            $params['house_id'] = $id;
            return true;
        }

        $params['house_id'] = $old->id;
        return true;
    }

    /**
     * 房源绑定小区
     * @param $params
     * @return bool
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public function bindVillage($params) {
        // 获取商圈id
        if (!$village = db('house_village')->where(['ajk_id' => $params['village_id']])->field('business_area,id')->find()) {
            throw new Exception('不存在该小区', RespCode::PARAMS_ERR);
        }
        // 获取商圈信息
        if (!$baData = db('business_area')->field('city_id,city_ids')->where(['id' => $village['business_area']])->find()) {
            throw new Exception('不存在该商圈', RespCode::PARAMS_ERR);
        }

        // 获取房源id
        $where = ['source_id' => $params['house_id']];
        switch ($params['source_id']) {
            case 1:
                $id = db('house_jd')->where($where)->value('house_id');
                break;
            case 2:
                $id = db('house_ali')->where($where)->value('house_id');
                break;
            default:
                $id = 0;
                break;
        }

        if (!$id) {
            throw new Exception('房源拍卖信息不存在', RespCode::PARAMS_ERR);
        }

        $params['village_id'] = $village['id'];
        // 更新绑定信息
        $uData = [
            'city_code'        => $baData['city_code'],
            'city_codes'       => $baData['city_codes'],
            'business_area_id' => $village['business_area'],
            'village_id'       => $params['village_id'],
        ];
        if (!$this->where(['id' => $id])->update($uData)) {
            throw new Exception('房源绑定小区失败', RespCode::PARAMS_ERR);
        }
        return true;
    }

    /**
     * 验证参数
     * @param $params
     * @param $fields
     * @throws Exception
     */
    public static function checkParams(&$params, $fields) {
        foreach ($fields as $key => $field) {
            if (!isset($params[$field]) || (empty($params[$field]) && $params[$field] !== 0))
                throw new Exception("{$field} 不能为空", RespCode::PARAMS_ERR);
        }
    }

    /**
     * 新增拍卖&房源数据
     * @param $data
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function addNewData($data, $sourceType) {
        list($houseData, $houseAuctionData) = self::handleData($data, 2, $sourceType);
        $auction_id = db("house_auction")->strict(false)->insertGetId($houseAuctionData);
        if (!$auction_id) throw new Exception("新增拍卖&房源数据 - 新增house_auction错误", RespCode::PARAMS_ERR);
        $houseData['auction_id'] = $auction_id;
        $house_id = db("house")->strict(false)->insertGetId($houseData);
        if (!$house_id) throw new Exception("新增拍卖&房源数据 - 新增house错误", RespCode::PARAMS_ERR);
        $res = db("house_auction")->where('id', $auction_id)->strict(false)->update(['house_id' => $house_id]);
        if ($res === false) throw new Exception("新增拍卖&房源数据 - 更新house_auction错误", RespCode::PARAMS_ERR);
    }

    /**
     *  同步拍卖、房源数据
     * _id、house_id、title、start_time、initial_price、deal_time、final_price、auction_status、type、enroll_num、remind_num
     * @param $params
     * @param $has_house_auction
     * @param $house_data
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function handleSyncData($params, $has_house_auction, $house_data) {
        $syncData = $params;
        //删除不需要的字段
        if (isset($syncData['_id'])) unset($syncData['_id']);
        if (isset($syncData['title'])) unset($syncData['title']);
        if (isset($syncData['house_id'])) unset($syncData['house_id']);
        if (isset($syncData['itime'])) unset($syncData['itime']);
        if (isset($syncData['id'])) unset($syncData['id']);
        //统一转换金额
        $syncData = price_arr_deal($syncData, 1);
        //绑定房源
        $syncData['house_id'] = $house_data['id'];
        $syncData['source_id'] = $params['house_id'];
        $syncData['soure_updatetime'] = time();

        $syncData['type'] == 4 ? $syncData['pay_selloff'] = $syncData['initial_price'] : $syncData['pay_selloff'] = 0;

        //房源有市场价就取房源的，$houseAuctionData['market_price']从新赋值
        if (!empty($house_data['market_price'])) $syncData['market_price'] = $house_data['market_price'];

        //重新计算折扣
        if (isset($syncData['initial_price']) && !empty($syncData['market_price'])) {
            if ($syncData['initial_price'] < $syncData['market_price']) {
                $syncData['discount'] = round($syncData['initial_price'] / $syncData['market_price'] * 10, 2);
                $syncData['discount'] < 1 && $syncData['discount'] = 0;
                $syncData['discount'] >= 10 && $syncData['discount'] = 10;
            }
        }

        //更新拍卖信息，所有字段更新
        if (db("house_auction")->where("source_id", $params['house_id'])->strict(false)->update($syncData) === false)
            throw new Exception("更新house_auction错误", RespCode::PARAMS_ERR);

        $houseUpdate = [];
        //如果房源market_price为空，更新为拍卖的market_price
        if (empty($house_data['market_price']) && isset($syncData['market_price'])) $houseUpdate['market_price'] = $syncData['market_price'];

        if (!empty($houseUpdate)) {
            if (db("house")->where("title", $params['title'])->strict(false)->update($houseUpdate) === false)
                throw new Exception("更新house错误", RespCode::PARAMS_ERR);
        }
    }

    /**
     * 已存在房源绑定新的拍卖信息
     * @param $data
     * @param $has_house
     * @param $sourceType
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function bindNewAuction($data, $has_house, $sourceType) {
        list($houseData, $houseAuctionData) = self::handleData($data, 1, $sourceType);
        //房源有市场价就取房源的，$houseAuctionData['market_price']从新赋值
        if (!empty($has_house['market_price'])) $houseAuctionData['market_price'] = $has_house['market_price'];

        //重新计算折扣
        $houseAuctionData['discount'] = -1;
        if (!empty($houseAuctionData['market_price'])) {
            if ($houseAuctionData['initial_price'] < $houseAuctionData['market_price']) {
                $houseAuctionData['discount'] = round($houseAuctionData['initial_price'] / $houseAuctionData['market_price'] * 10, 2);
                $houseAuctionData['discount'] < 1 && $houseAuctionData['discount'] = 0;
                $houseAuctionData['discount'] >= 10 && $houseAuctionData['discount'] = 10;
            }
        }

        $houseAuctionData['house_id'] = $has_house['id'];
        if (!$auction_id = db("house_auction")->strict(false)->insertGetId($houseAuctionData))
            throw new Exception("已存在房源绑定新的拍卖信息 - 新增house_auction错误", RespCode::PARAMS_ERR);

        //更新房源对应拍卖id
        $houseUpdate['auction_id'] = $auction_id;
        //如果房源market_price为空，更新为拍卖的market_price
        if (empty($has_house['market_price']) && isset($houseAuctionData['market_price']))
            $houseUpdate['market_price'] = $houseAuctionData['market_price'];
        //更新房源source_url
        if (isset($houseAuctionData['source_url'])) $houseUpdate['source_url'] = $houseAuctionData['source_url'];

        if (db("house")->where('id', $has_house['id'])->strict(false)->update($houseUpdate) === false)
            throw new Exception("已存在房源绑定新的拍卖信息 - 更新house错误", RespCode::PARAMS_ERR);
    }

    /**
     * 房源、拍卖数据处理
     * @param $params
     * @return array
     * @throws Exception
     */
    public static function handleData($params, $type, $sourceType) {
        $params = price_arr_deal($params, 1);//金额转换
        $houseData = [];
        if ($type == 1) goto Auction;
        if (isset($params['address'])) $address = $params['province'] . $params['city'] . $params['area'] . $params['address'];
        else $address = $params['title'];
        $address_info = self::getAddressInfoByMaps($address, $params['city']);
        $province = $address_info['province'];
        $city = $address_info['city'];
        $area = $address_info['area'];
        $city_code = $address_info['city_code'];
        $map_address = $address_info['map_address'];
        $lng = $address_info['lng'];
        $lat = $address_info['lat'];

        //房源数据处理
        $houseData['village_id'] = 0;
        $houseData['business_area_id'] = 0;
        $houseData['auction_id'] = 0;
        $houseData['source_type'] = $sourceType;
        $houseData['source_url'] = $params['source_url'] ?? '';
        $houseData['anjuke_url'] = '';
        $houseData['title'] = $params['title'];
        $houseData['sn'] = md5($params['title']);
        $houseData['cover'] = $params['cover'] ?? "";
        $houseData['province'] = $province ?? $params['province'] ?? "";
        $houseData['city'] = $city ?? $params['city'] ?? '';
        $houseData['area'] = $area ?? $params['area'] ?? "";
        $houseData['city_code'] = $city_code ?? 0;
        $houseData['city_codes'] = $pCodes ?? "";
        $houseData['address'] = $params['address'] ?? $map_address ?? "";
        $houseData['map_address'] = $map_address ?? "";
        $houseData['district'] = $params['district'] ?? "";
        $houseData['floor'] = $params['floor'] ?? 0;
        $houseData['max_floor'] = $params['max_floor'] ?? 0;
        $houseData['bedroom'] = $params['bedroom'] ?? 0;
        $houseData['livingroom'] = $params['livingroom'] ?? 0;
        $houseData['build_time'] = $params['build_time'] ?? 0;
        $houseData['build_area'] = isset($params['build_area']) ? $params['build_area'] * 10000 : 0;
        $houseData['renovation_type'] = $params['renovation_type'] ?? 0;
        $houseData['house_type_id'] = 1;
        $houseData['house_type_ids'] = '';
        $houseData['house_cate'] = 0;
        $houseData['living_type'] = $params['living_type'] ?? 1;
        $houseData['lease_remark'] = $params['lease_remark'] ?? '';
        $houseData['property_type'] = $params['property_type'] ?? 1;
        $houseData['warrant'] = $params['warrant'] ?? '';
        $houseData['anjuke_price'] = 0;
        $houseData['itime'] = time();
        $houseData['utime'] = 0;
        $houseData['source_utime'] = time();
        $houseData['staff_id'] = 0;
        $houseData['important'] = 0;
        $houseData['is_shelf'] = 0;
        $houseData['is_update'] = 0;
        $houseData['is_complete'] = 0;
        $houseData['customer_count'] = 0;
        $houseData['pic'] = $params['pics'] ?? '';
        $houseData['lng'] = $lng;
        $houseData['lat'] = $lat;
        $houseData['location'] = Db::raw("POINT('{$lng}', '{$lat}')");
        $houseData['from'] = 1;
        $houseData['bulu_time'] = 0;
        $houseData['market_price'] = $params['market_price'] ?? 0;
        $houseData['source_province'] = $params['province'] ?? '';
        $houseData['source_city'] = $params['city'] ?? '';
        $houseData['source_area'] = $params['area'] ?? '';

        //拍卖数据处理
        Auction:
        $houseAuctionData['house_id'] = 0;
        $houseAuctionData['source_id'] = $params['house_id'];
        $houseAuctionData['source_type'] = $sourceType;
        $houseAuctionData['court_name'] = $params['court_name'] ?? "";
        $houseAuctionData['start_time'] = $params['start_time'] ?? 0;
        $houseAuctionData['end_time'] = $params['end_time'] ?? 0;
        $houseAuctionData['institution'] = $params['contact_name'] ?? "";
        $houseAuctionData['contact_name'] = $params['contact_name'] ?? "";
        $houseAuctionData['contact_tel'] = $params['contact_tel'] ?? "";
        $houseAuctionData['initial_price'] = $params['initial_price'] ?? 0;
        $houseAuctionData['bond'] = $params['bond'] ?? 0;
        $houseAuctionData['consult_price'] = $params['consult_price'] ?? 0;
        $houseAuctionData['market_price'] = $params['market_price'] ?? 0;
        $discount = -1;
        if (!empty($params['market_price'])) {
            // 当初始价 小于等于市场价时，才计算折扣
            if ($params['initial_price'] < $params['market_price']) {
                $discount = round($params['initial_price'] / $params['market_price'] * 10, 2);
                $discount < 1 && $params['discount'] = 0;
                $discount >= 10 && $params['discount'] = 10;
            }
        }
        $houseAuctionData['discount'] = $discount;
        $houseAuctionData['type'] = in_array(isset($params['type']) ?? 0, [1, 2, 3, 4, 5, 6]) ? $params['type'] : 0;
        $houseAuctionData['pay_selloff'] = $houseAuctionData['type'] == 4 ? $houseAuctionData['initial_price'] : 0;
        $houseAuctionData['predict_price'] = 0;
        $houseAuctionData['price_lower_offset'] = $params['price_lower_offset'] ?? 0;
        $houseAuctionData['final_price'] = $params['final_price'] ?? 0;
        $houseAuctionData['tail_money_date'] = 0;
        $houseAuctionData['enroll_num'] = $params['enroll_num'] ?? 0;
        $houseAuctionData['access_num'] = $params['access_num'] ?? 0;
        $houseAuctionData['remind_num'] = $params['remind_num'] ?? 0;
        $houseAuctionData['itime'] = time();
        $houseAuctionData['day_itime'] = strtotime(date("Y-m-d"));
        $houseAuctionData['month_itime'] = strtotime(date("Y-m"));
        $houseAuctionData['utime'] = 0;
        $houseAuctionData['soure_updatetime'] = time();
        $houseAuctionData['deal_time'] = $params['deal_time'] ?? 0;
        $houseAuctionData['bid_count'] = $params['bid_count'] ?? 0;
        $houseAuctionData['auction_status'] = $params['auction_status'] ?? 0;
        $houseAuctionData['source_url'] = $params['source_url'] ?? "";

        return [
            $houseData,
            $houseAuctionData
        ];
    }

    /**
     * 获取地理信息
     * @param $address
     * @param $lng
     * @param $lat
     * @param $city
     * @return array
     * @throws Exception
     */
    public static function getAddressInfoByMaps($address, $city) {
        //通过地址解析经纬度
        $res1 = BaiDu::placeSearch($address, $city, '住宅');
        $lat = $res1['results'][0]['location']['lat'] ?? 0;
        $lng = $res1['results'][0]['location']['lng'] ?? 0;
        if (!empty($lat) && !empty($lng)) {
            $res2 = BaiDu::getByLocation($lat, $lng);
            if (!empty($res2['result'])) {
                $lng = round($res2['result']['location']['lng'] ?? $lng, 6);
                $lat = round($res2['result']['location']['lat'] ?? $lat, 6);
                $data = [
                    'province'    => $res2['result']['addressComponent']['province'] ?? '',
                    'city'        => $res2['result']['addressComponent']['city'] ?? '',
                    'area'        => $res2['result']['addressComponent']['district'] ?? '',
                    'district'    => $res2['result']['addressComponent']['street'] ?? '',
                    'map_address' => $res2['result']['formatted_address'],
                    'city_code'   => $res2['result']['addressComponent']['adcode'] ?? 0,
                    'lng'         => $lng,
                    'lat'         => $lat,
                ];
            }
        } else {
            $data = [
                'province'    => '',
                'city'        => '',
                'area'        => '',
                'district'    => '',
                'map_address' => '',
                'city_code'   => 0,
                'lng'         => 0,
                'lat'         => 0,
            ];
        }
        return $data;
    }


}
